package com.xiaohe.gulimall.authserver.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xiaohe.common.utils.HttpUtils;
import com.xiaohe.common.utils.R;
import com.xiaohe.common.vo.MemberResponseVo;
import com.xiaohe.gulimall.authserver.feign.MemberFeignService;
import com.xiaohe.gulimall.authserver.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class OAth2Controller {


    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String OAuth2Controller(@RequestParam("code") String code, HttpSession session) throws Exception {

        Map<String, String> map = new HashMap<>();
        map.put("client_id","1571308047");
        map.put("client_secret","d43df0d2a89b5882130cc4fc706c0b05");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        //根据code换取Access_token
        //HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", null, null, map);
        //1、根据用户授权返回的code换取access_token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());
        System.out.println(response.getStatusLine().getStatusCode());
        if(response.getStatusLine().getStatusCode() ==200){
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //当前用户如果第一次登录，将该用户注册进来
            //登录或者注册该用户
            R oauthLogin = memberFeignService.oauth2Login(socialUser);
            if (oauthLogin.getCode() ==0){
                MemberResponseVo data = (MemberResponseVo) oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {
                });
                System.out.println("登录成功：用户信息"+data);
                session.setAttribute("loginUser",data);
                log.info("登录成功，用户：{}",data);
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
